package com.leon.alishop.web.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.SimpleHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.leon.alishop.core.util.AliShopStringUtils;

public class AlishopImageUtils {

	private static Logger log = LoggerFactory.getLogger(AlishopImageUtils.class);
	
	private static HttpClient client;
	
	static{
		client = new HttpClient(new SimpleHttpConnectionManager());
	}
	
	public static boolean deleteAllFile(String path){
		boolean flag = false;
	       File file = new File(path);
	       if (!file.exists()) {
	         return flag;
	       }
	       if (!file.isDirectory()) {
	         return flag;
	       }
	       String[] tempList = file.list();
	       File temp = null;
	       for (int i = 0; i < tempList.length; i++) {
	          if (path.endsWith(File.separator)) {
	             temp = new File(path + tempList[i]);
	          } else {
	              temp = new File(path + File.separator + tempList[i]);
	          }
	          if (temp.isFile()) {
	             temp.delete();
	          }
	          if (temp.isDirectory()) {
	        	 deleteAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
	             delFolder(path + "/" + tempList[i]);//再删除空文件夹
	             flag = true;
	          }
	       }
	       return flag;
	}
	
	 public static void delFolder(String folderPath) {
	     try {
	    	deleteAllFile(folderPath); //删除完里面所有内容
	        String filePath = folderPath;
	        filePath = filePath.toString();
	        java.io.File myFilePath = new java.io.File(filePath);
	        myFilePath.delete(); //删除空文件夹
	     } catch (Exception e) {
	       e.printStackTrace();
	     }
	 }
	
	public static void downloadImgToLocal(String path,String prefix,String[] imgs) throws HttpException, IOException{
		createPathIfInexi(path);
        if(null != imgs){
        	GetMethod get;
        	File storeFile;
        	for (String img : imgs) {
        		try {
        			get = new GetMethod(encodeUrl(img));
        			client.executeMethod(get);
            		storeFile = new File(path + prefix + splitName(img));  
            		FileOutputStream output = new FileOutputStream(storeFile);  
            		output.write(get.getResponseBody());  
            		output.close();
				} catch (Exception e) {
					log.error("下载图片出错："+img);
				}
        		
			}
        }
    }
	
	public static String splitImgMinToBigUrl(String imgSrc){
		if(imgSrc == null)
			return null;
		int indexof = imgSrc.lastIndexOf("_");
		if(indexof > 0){
			imgSrc = imgSrc.substring(0,indexof);
			if(imgSrc.indexOf(".jpg") > 0
					|| imgSrc.indexOf(".png")>0
					|| imgSrc.indexOf(".gif")>0
					|| imgSrc.indexOf(".jpeg")>0
					|| imgSrc.indexOf(".bmp")>0)
				return imgSrc;
		}
		return imgSrc;
	}
	
	private static void createPathIfInexi(String path){
		File fd = null;  
        try {  
            fd = new File(path);  
            if (!fd.exists()) {  
                fd.mkdirs();  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            fd = null;  
        }  
	}
	
	private static String encodeUrl(String url){
		int len = url.length();
		char c;
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < len; i++) {
			c = url.charAt(i);
			if(AliShopStringUtils.isCJK(c)){
				try {
					sb.append(URLEncoder.encode(String.valueOf(c), "UTF-8"));
				} catch (UnsupportedEncodingException e) {
					sb.append(c);
				}
			}else{
				sb.append(c);
			}
		}
		return sb.toString();
	}
	
	private static String splitName(String imgSrc){
		if(imgSrc == null)
			return null;
		int indexof = imgSrc.lastIndexOf("/");
		if(indexof > 0)
			imgSrc = imgSrc.substring(indexof+1,imgSrc.length());
		indexof = imgSrc.lastIndexOf("\\");
		if(indexof > 0)
			return imgSrc.substring(indexof+1,imgSrc.length());
		return imgSrc;
	}
}
